package com.msf.tutorial.java8.chapter6;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

public class IteratorExample {

    /**
     * 用for-each循环外部迭代
     */
    public static void iteratorUseFor(List<Menu> menus) {
        List<String> names = new ArrayList<>();
        for (Menu menu : menus) {
            names.add(menu.getName());
        }
    }

    /**
     * 用Iterator循环外部迭代
     */
    public static void iteratorUseIterator(List<Menu> menus) {
        List<String> names = new ArrayList<>();
        Iterator<Menu> iterator = menus.iterator();
        while (iterator.hasNext()) {
            Menu menu = iterator.next();
            names.add(menu.getName());
        }
    }

    /**
     * 用Stream内部迭代
     */
    public static void iteratorUseStream(List<Menu> menus) {
        List<String> names = menus.stream()
                .map(Menu::getName)
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        List<Menu> list = Arrays.asList(new Menu("menu1"), new Menu("menu2"), new Menu("menu3"));
        iteratorUseStream(list);
    }

}

class Menu {
    private String name;

    public Menu(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

